<!-- 资产装置列表信息 -->
<template>
  <div class="q-pa-md bg-white">
    <div class="row q-mb-md">
      <div style="width: 230px" class="q-mt-xs q-mr-sm">
        <q-select dense options-dense outlined v-model="headerSeach" :options="deviceNameOptions" />
      </div>
      <div v-show="headerSeach" style="width: 200px" class="q-mr-sm q-mt-xs">
        <q-input outlined v-model="queryList[seachContent[headerSeach]]" dense />
      </div>
      <q-btn class="q-mr-sm q-mt-xs borderRadius" unelevated icon="search" padding="8px 8px 7px" color="primary"
        label="搜索" @click="handlerSearch" />
      <q-btn class="q-mr-sm q-mt-xs borderRadius" unelevated color="primary" padding="8px 8px 7px" label="复位搜索"
        @click="handleResetSearch" />
      <q-btn class="q-mr-sm q-mt-xs borderRadius" unelevated color="primary" padding="8px 8px 7px" label="添加关注"
        @click="dialogTableVisible = true" />
    </div>
    <q-markup-table flat style="max-height:530px;">
      <thead>
        <th v-for="column in columns" :key="column.name" :class="column.align">
          {{ column.label }}
          <q-icon v-if="column.isSort" class="cursor-pointer" size="18px"
            :name="descending ? 'expand_less' : 'expand_more'" @click="handlerSort" />
        </th>
        <th class="text-center">操作</th>
      </thead>
      <tbody>
        <div v-if="loading">
          <q-inner-loading showing color="grey" />
        </div>
        <tr v-for="row in dataList" :key="row.id">
          <td v-for="column in columns" :key="column.name" :class="column.align">
            <span v-if="!column.isImg">{{ row[column.name] }}</span>
            <span v-else>
              <img style="height: 28px;" :src="row[column.name]" alt="暂无图片">
            </span>
          </td>
          <td class="text-center">
            <DetailBtn @click="handlerDetailSensor(row)" />
            <DeleteBtn :btnTitle="'取消关注'" @click="handleDelete(row)" />
          </td>
        </tr>
      </tbody>
    </q-markup-table>
    <!-- 分页 -->
    <Pagination :pageSizes="['5条/页', '10条/页', '20条/页', '30条/页']" @updatePage="updatePage" @updateSizes="updateSizes"
      :pagination="pagination" @handlerRefresh="handlerRefresh" />
  </div>

  <!-- 详情 提示框 -->
  <DetailDialog :isShowDetail="isShowDetail" :detailList="detailList" :msg="detailMsg" :titleName="'资产详情'"
    @closeDetail="closeDetail" />
  <!-- 删除 提示框 -->
  <DeleteDialog :isShowDelete="isShowDelete" :tipInfo="titelCancel[tipInfo]" @closeDeleteDialog="closeDeleteDialog"
    @confirmDelete="confirmDelete()" />

  <!-- 资产信息 -->
  <q-dialog v-model="dialogTableVisible">
    <AssetInfoMore :dialog-table-visible="dialogTableVisible" @selectedEvent="selectedEvent"
      @closeDialog="closeDialog" />
  </q-dialog>

</template>

<script>
import { ref } from 'vue'
import DetailDialog from 'src/components/detailDialog/index'
import DeleteDialog from 'src/components/deleteDialog/index'
import AssetInfoMore from 'src/pages/common/assetInfoMore'
import { getAssetDetail } from 'src/api/asset'
import { fetchConPerson, setIsConcerns } from 'src/api/systemtWarning'
import hosts from 'src/utils/host.js'
import { mapGetters } from 'vuex';
import DetailBtn from 'src/components/btnCom/detailBtn'
import DeleteBtn from 'src/components/btnCom/deleteBtn'
import Pagination from 'src/components/pagination'

export default {
  data() {
    return {
      dataList: [],
      filter: ref(''),

      columns: [
        { name: 'idIndex', required: true, label: 'ID', align: 'text-center', field: 'idIndex', isSort: true, isImg: false },
        { name: 'equip_img', required: true, label: '资产图片', align: 'text-center', field: 'equip_img', isImg: true },
        { name: 'equip_name', required: true, label: '资产名称', align: 'text-center', field: 'equip_name', isImg: false },
        { name: 'equip_sn', align: 'text-center', label: '资产编号', field: 'equip_sn', isImg: false },
      ],

      // 表格头部
      headerSeach: ref(),
      deviceNameOptions: [],
      // 右侧表头选择
      visibleColumns: ref([]),
      queryList: {
        page: 1,
        page_size: 10,
        ordering: 'id'
      },
      pagination: { // 分页
        sortBy: 'desc', // 列名
        descending: false, // 是否按照降序排序
        page: 1, // 页码（当前显示第几页的数据）
        rowsPerPage: 10, // 每页多少行
        rowsNumber: 1 // 共多少条
      },
      loading: false,
      isShowDetail: false,
      detailList: [],
      detailMsg: '',
      seachContent: {
        '资产ID': 'equip_id',
        '资产名称': 'equip_name',
        '资产编号': 'equip_sn'
      },
      setAssetId: 0,
      isShowDelete: false,
      dialogTableVisible: false,
      tipInfo: 'concern',
      titelCancel: {
        concern: '确定关注该资产吗？',
        cancel: '确定取消关注该资产吗？'
      },
      descending: false

    }
  },

  components: {
    DetailDialog,
    DeleteDialog,
    AssetInfoMore,
    DetailBtn,
    DeleteBtn,
    Pagination
  },

  computed: {
    ...mapGetters(['themeColor'])
  },
  watch: {
  },
  beforeCreate() {
  },
  mounted() {
    this.feathOranizerList()
    this.handleSelect()
  },

  methods: {
    // 刷新
    handlerRefresh() {
      this.handleResetSearch()
    },
    /**
     * 搜索
     */
    handlerSearch() {
      this.pagination.page = 1
      this.feathOranizerList()
    },
    /**
     * 复位搜索
     */
    handleResetSearch() {
      this.queryList = {
        ordering: 'id',
        page: 1,
        page_size: 10,
        concerns_uid: localStorage.getItem("user_id_GFYW")
      }
      this.headerSeach = ''
      this.feathOranizerList()
    },
    /**
     * 获取资产信息的列表
     */
    feathOranizerList() {
      this.loading = true
      this.queryList.ordering = 'id'
      this.queryList.page = this.pagination.page
      this.queryList.page_size = this.pagination.rowsPerPage
      this.queryList.concerns_uid = localStorage.getItem("user_id_GFYW")
      fetchConPerson(this.queryList).then(res => {
        const { status, data, totalCounts } = res
        this.pagination.rowsNumber = totalCounts
        if (status === 200) {
          this.dataList = []
          if (data && data.length > 0) {
            data.forEach((item, index) => {
              // 图片路径
              if (item.equip_img && item.equip_img.indexOf('http://') < 0) {
                if (item.equip_img.split('/')[0] === '') item.equip_img = item.equip_img.substr(1, item.equip_img.length - 1)
                item.equip_img = hosts + item.equip_img
              }
              if (this.queryList.ordering === 'id') {
                item.idIndex = index + 1
              } else {
                item.idIndex = data.length - index
              }
              this.dataList.push(item)
            });
          }
        }
        this.loading = false
      }).catch(_ => {
        this.loading = false
      })
    },
    /**
     * 详情
     */
    handlerDetailSensor(val) {
      if (val) {
        getAssetDetail({ dev_base_id: val.equip_id }).then(res => {
          this.detailList = []
          const { data, status, msg } = res
          if (status === 200) {
            this.detailList.push({ label: '资产编码', key: data.assets_sn })
            this.detailList.push({ label: '名称', key: data.name })
            this.detailList.push({ label: '类型', key: data.type_id })
            this.detailList.push({ label: '型号', key: data.model })
            this.detailList.push({ label: '序列号', key: data.sn })
            this.detailList.push({ label: '制造商', key: data.vendor })
            this.detailList.push({ label: '图片', img: data.img })
            this.detailList.push({ label: '安放位置', key: data.location })
            this.detailList.push({ label: '入厂日期', key: data.purchase_date })
            this.detailList.push({ label: '出厂日期', key: data.manufacture_date })
            this.detailList.push({ label: '创建日期', key: data.create_time })
            this.detailList.push({ label: '更新日期', key: data.modify_time })
            this.detailList.push({ label: '首次启用日期', key: data.first_use_date })
            this.detailList.push({ label: '主电机功率', key: data.main_motor_power })
            this.detailList.push({ label: '最小生产速率', key: data.production_speed_min })
            this.detailList.push({ label: '最大生产速率', key: data.production_speed_max })
          } else {
            this.$q.notify({
              type: 'warning',
              message: msg
            })
          }
        })
      }
      this.isShowDetail = true
    },
    /**
     * 关闭详情提示框
     */
    closeDetail() {
      this.isShowDetail = false
    },
    /**
     * 处理数据
     */
    handleSelect() {
      if (this.deviceNameOptions.length > 0) this.deviceNameOptions = []
      this.deviceNameOptions.push('')
      this.visibleColumns = []
      this.columns.forEach((item, index) => {
        if (index < 6) {
          this.visibleColumns.push(item.name)
        }
        // 下拉框的数据
        if (item.label === '资产名称' || item.label === '资产编号') this.deviceNameOptions.push(item.label)
      })
    },
    /**
    * 取消关注
    */
    handleDelete(val) {
      this.equipInfo = Object.assign({}, val)
      this.isShowDelete = true
      this.tipInfo = 'cancel'
      if (val) {
        this.cancalQuery = {
          concerns_uid: val.concerns_uid
        }
      }
      if (this.pagination.page > 1 && this.pagination.rowsNumber % this.pagination.rowsPerPage === 1) {
        this.pagination.page -= 1
      }
    },
    /**
     * 资产 - 确定取消关注
     */
    confirmDelete() {
      let queryTemp = {}
      if (!this.equipInfo) return
      queryTemp.equip_id = this.equipInfo.equip_id
      queryTemp.is_concerns = false
      queryTemp.concerns_uid = localStorage.getItem('user_id_GFYW')

      setIsConcerns(queryTemp).then(res => {
        const { status, msg } = res
        if (status === 200) {
          this.isShowDelete = false
          this.feathOranizerList()
          this.$q.notify({
            type: 'positive',
            position: 'top',
            message: `已取消关注！`
          })
        } else {
          this.$q.notify({
            type: 'positive',
            position: 'top',
            message: msg
          })
        }
      })
    },
    /**
     * 关闭删除提示框
     */
    closeDeleteDialog() {
      this.isShowDelete = false
    },
    /**
     * 关闭对话框
     */
    closeDialog(bool) {
      this.dialogTableVisible = false
    },
    selectedEvent(selection) {
      let queryTemp = {}
      queryTemp.is_concerns = true
      queryTemp.concerns_uid = localStorage.getItem('user_id_GFYW')
      selection.map((item, i) => {
        queryTemp.equip_id = item
        setIsConcerns(queryTemp).then(res => {
          if (res.status === 200) {
            if (selection.length - 1 == i) {
              this.dialogTableVisible = false
              this.feathOranizerList()
              this.$q.notify({
                type: 'positive',
                position: 'top',
                message: '添加成功！'
              })
            }
          }
        })
      })
    },
    /**
     * 排序
     */
    handlerSort() {
      this.descending = !this.descending
      this.dataList.reverse()
    },
    // 切换当前页数
    updatePage(val) {
      if (!val) return
      this.pagination.page = val * 1
      this.feathOranizerList()
    },
    // 切换每页的行数
    updateSizes(val) {
      this.pagination.rowsPerPage = parseFloat(val)
      this.feathOranizerList()
    },
  }
}

</script>
<style lang='scss' scoped>
// 固定操作列
.my-sticky-column-table {
  tr:first-child {
    th:last-child {
      background: #fff;
    }
  }

  td {
    &:last-child {
      background: #fff;
    }
  }

  th:last-child,
  td:last-child {
    position: sticky;
    right: 0;
    z-index: 1;
  }
}

// 弹出的对话框样式
.dialog-form-container {
  ul {
    li {
      height: 42px;
      line-height: 42px;
      white-space: nowrap;
      margin-bottom: 30px;

      >span {
        &:first-child {
          display: inline-block;
          width: 150px;
          margin-right: 5px;
        }

        &:last-child {
          display: inline-block;
          width: 200px;

          >.q-input {
            width: 200px;
          }
        }
      }
    }
  }
}

.click-row {
  background-color: rgba(0, 0, 0, 0.06) !important;
}
</style>
